/**
 * 文件名    ： DruidConfig.java
 * 版权       : XX科技有限公司。
 * 描述       : <描述>
 * 修改时间：2017年5月30日
 * 修改内容：<修改内容>
 */
package com.example.demo.application.common.config;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.example.demo.application.common.MyConstants;
import com.example.demo.application.common.encrypt.AES;
import com.example.demo.application.common.encrypt.EncryptConfig;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

//使用 Hikari 链接池 时 ， 放开下面的注释
//@Configuration
public class MyHikariConfig {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Value("${spring.datasource.url}")
	private String dbUrl;
	
	@Value("${spring.datasource.username}")
	private String username;
	
	@Value("${spring.datasource.password.prefix}")
	private String passwordkey1;
	
	@Value("${spring.datasource.password.suffix}")
	private String passwordkey2;
	
	@Value("${spring.datasource.driver-class-name}")
	private String driverClassName;
	
	@Value("${spring.datasource.minIdle}")
	private int minIdle;
	
	@Value("${spring.datasource.maxActive}")
	private int maxActive;
	
	@Value("${spring.datasource.maxWait}")
	private int maxWait;
	
	
	@Value("${root.key1.config.file.path}")
	private String rootKey1FilePath;
	
	@Value("${root.key2.config.file.path}")
	private String rootKey2FilePath;
	
	@Value("${redis.config.file.path}")
	private String redisConfigFilePath;
	
	
	
	@Bean
	public DataSource druidDataSource(){ 
		return this.hikariDs();
	}
	
	private DataSource hikariDs() {
		HikariConfig config = new HikariConfig();
		
		if (StringUtils.isBlank(EncryptConfig.rootKey)) {
			this.init();
		}
		if(StringUtils.isBlank(EncryptConfig.redisConfigFilePath)) {
			EncryptConfig.redisConfigFilePath=redisConfigFilePath;
		}
		
		config.setJdbcUrl(this.dbUrl); //数据源
		config.setUsername(username);  //用户名
		String mysqlKey1;
		try {
			mysqlKey1 = AES.decrypt(passwordkey1, EncryptConfig.rootKey);
			String mysqlKey2 = AES.decrypt(passwordkey2, EncryptConfig.rootKey);
			//			47c95b226ebf4287893007c834b194c6
			String pass = mysqlKey1+mysqlKey2;
			config.setPassword(pass); //密码
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		config.setDriverClassName(driverClassName); 
		config.addDataSourceProperty("destroy-method", "shutdown");		
        config.addDataSourceProperty("cachePrepStmts", "true"); //是否自定义配置，为true时下面两个参数才生效
        config.addDataSourceProperty("prepStmtCacheSize", "250"); //连接池大小默认25，官方推荐250-500
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); //单条语句最大长度默认256，官方推荐2048
        config.addDataSourceProperty("useServerPrepStmts", "true"); //新版本MySQL支持服务器端准备，开启能够得到显著性能提升
        config.addDataSourceProperty("useLocalSessionState", "true");
        config.addDataSourceProperty("useLocalTransactionState", "true");
        config.addDataSourceProperty("rewriteBatchedStatements", "true");
        config.addDataSourceProperty("cacheResultSetMetadata", "true");
        config.addDataSourceProperty("cacheServerConfiguration", "true");
        config.addDataSourceProperty("elideSetAutoCommits", "true");
        config.addDataSourceProperty("maintainTimeStats", "false");
        config.setMinimumIdle(this.minIdle);
        config.setMaximumPoolSize(this.maxActive);
        config.setIdleTimeout(this.maxWait);
//        config.addDataSourceProperty("minimum-idle", "1");
//        config.addDataSourceProperty("maximum-pool-size", "2");
//        config.addDataSourceProperty("idle-timeout", "5000");
        
        HikariDataSource ds = new HikariDataSource(config);
        return ds;
		
		
	}
	
	/**
	 * <功能> 初始化 <详细描述> 配置 初始化
	 * 
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	private synchronized void init() {
		String key1 = "";
		String key2 = "";
		ResourceBundle bundle = null;
		try {
			BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(rootKey1FilePath));
			bundle = new PropertyResourceBundle(inputStream);
			key1 = bundle.getString("root_key_1").trim();
			inputStream.close();
		} catch (IOException e1) {
			logger.error(" RootKey1File : ", e1);
		}
		if (StringUtils.isBlank(key1)) {
			logger.error("[RootKey1File] is not found!");
			throw new IllegalArgumentException("[RootKey1File] is not found!");
		}

		try {
			BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(rootKey2FilePath));
			bundle = new PropertyResourceBundle(inputStream);
			key2 = bundle.getString("root_key_last").trim();
			inputStream.close();
		} catch (IOException e1) {
			logger.error(" RootKey2File init : ", e1);
		}
		if (StringUtils.isBlank(key2)) {
			logger.error("[RootKey2File] is not found!");
			throw new IllegalArgumentException("[RootKey2File] is not found!");
		}
		bundle = null;

		// 解密
		String deString;
		try {
			deString = AES.decrypt(key1, MyConstants.ROOT_FATHER_KEY);
			String deString_last = AES.decrypt(key2, MyConstants.ROOT_FATHER_KEY);
			EncryptConfig.rootKey = deString + deString_last;
		} catch (Exception e) {
			logger.error("rootKey AES.decrypt ERR !");
			throw new IllegalArgumentException("rootKey AES.decrypt ERR !");
		}
	}
}